﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Kinect;
using System.IO;

namespace KinectStudio.ModuliVisione
{
    /// <summary>
    /// Interaction logic for Stereoscopico.xaml
    /// </summary>
    public partial class Stereoscopico : Window
    {
        #region Variabili
            private KinectSensor sensore;
            private WriteableBitmap colorBitmap;
            private DepthImagePixel[] depthPixels;
            private byte[] colorPixels;
        #endregion

        public Stereoscopico()
        {
            InitializeComponent();
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem menuCliccato = (MenuItem)e.OriginalSource;
            switch (menuCliccato.Header.ToString())
            {
                case "Esci":
                    this.Close();
                    break;
            }
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            foreach(KinectSensor possibileSensore in KinectSensor.KinectSensors){
                if (possibileSensore.Status == KinectStatus.Connected)
                {
                    sensore = possibileSensore;
                    break;
                }
            }
            if (this.sensore != null)
            {
                this.sensore.DepthStream.Enable(DepthImageFormat.Resolution640x480Fps30);
                this.depthPixels = new DepthImagePixel[this.sensore.DepthStream.FramePixelDataLength];
                this.colorPixels = new byte[this.sensore.DepthStream.FramePixelDataLength * sizeof(int)];
                this.colorBitmap = new WriteableBitmap(this.sensore.DepthStream.FrameWidth, this.sensore.DepthStream.FrameHeight, 96, 96, PixelFormats.Bgr32, null);
                this.ui_anteprima.Source = this.colorBitmap;
                this.sensore.DepthFrameReady += this.SensorDepthFrameReady;
                try
                {
                    this.sensore.Start();
                }
                catch (IOException)
                {
                    this.sensore = null;
                }
            }
            if (this.sensore == null)
            {
                MessageBox.Show("Nessun Kinect Rilevato", "Errore", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void SensorDepthFrameReady(object sender, DepthImageFrameReadyEventArgs e)
        {
            using (DepthImageFrame depthFrame = e.OpenDepthImageFrame())
            {
                if (depthFrame != null)
                {
                    // Copy the pixel data from the image to a temporary array
                    depthFrame.CopyDepthImagePixelDataTo(this.depthPixels);

                    // Get the min and max reliable depth for the current frame
                    int minDepth = depthFrame.MinDepth;
                    int maxDepth = depthFrame.MaxDepth;

                    // Convert the depth to RGB
                    int colorPixelIndex = 0;
                    for (int i = 0; i < this.depthPixels.Length; ++i)
                    {
                        // Get the depth for this pixel
                        short depth = depthPixels[i].Depth;

                        // To convert to a byte, we're discarding the most-significant
                        // rather than least-significant bits.
                        // We're preserving detail, although the intensity will "wrap."
                        // Values outside the reliable depth range are mapped to 0 (black).

                        // Note: Using conditionals in this loop could degrade performance.
                        // Consider using a lookup table instead when writing production code.
                        // See the KinectDepthViewer class used by the KinectExplorer sample
                        // for a lookup table example.
                        byte intensity = (byte)(depth >= minDepth && depth <= maxDepth ? depth : 0);

                        // Write out blue byte
                        this.colorPixels[colorPixelIndex++] = intensity;

                        // Write out green byte
                        this.colorPixels[colorPixelIndex++] = intensity;

                        // Write out red byte                        
                        this.colorPixels[colorPixelIndex++] = intensity;

                        // We're outputting BGR, the last byte in the 32 bits is unused so skip it
                        // If we were outputting BGRA, we would write alpha here.
                        ++colorPixelIndex;
                    }

                    // Write the pixel data into our bitmap
                    this.colorBitmap.WritePixels(
                        new Int32Rect(0, 0, this.colorBitmap.PixelWidth, this.colorBitmap.PixelHeight),
                        this.colorPixels,
                        this.colorBitmap.PixelWidth * sizeof(int),
                        0);
                }
            }
        }

        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (this.sensore != null)
            {
                this.sensore.Stop();
            }
        }
    }
}
